<?php

/**
 * 批量调用paas接口
 * Date: 2019/03/29
 */

namespace Lib\Paas;

use Lib\Base\Common;
use Lib\Base\Validate;

class BatchQuery extends Base
{
    public function __construct($sData = [])
    {
        parent::__construct($sData);
    }

    /**
     * 批量请求
     *
     * @param array $request 请求参数
     * [
     *      [
     *          'apiName' => '接口名称',
     *          'getData' => [
     *              'name1' => 'value1',
     *              'name2' => 'value2',
     *               ...
     *          ],
     *          'postData' => array : [
     *              'name1' => 'value1',
     *              'name2' => 'value2',
     *              ...
     *              ] | string: 'post传递的数据的字符串形式'
     *              'postType' => '0:key=value数组，1:json, 2:查询字符串'
     *      ]
     *      ...
     * ]
     * 数字下标的多维数组，每个数组包含对应的接口请求信息
     * getData 对应的接口请求的get参数，name1，name2，...为参数名称，value1，value2，...为对应的参数值
     * postData array|string
     * array:对应的接口请求的post参数，name1，name2，...为参数名称，value1，value2，...为对应的参数值
     * string:要post传递的数据的字符串形式。
     * postType: post数据的传递方式，0:key=value数组，1:json, 2:查询字符串，即key1=value1&key2=value2&...。postData为array类型时有效。
     *
     * @return array
     * [
     *      'iRet' => '=0-成功，!=0-失败',  //接口是否成功，需要结合data中接口返回值进行判断
     *      'sMsg'=>'接口调用相关提示信息',
     *      'data' => [
     *          '0' => [
     *              '接口返回数据'
     *          ]
     *          '1' => [参考0],
     *          ...
     *      ]
     * ]
     * 每个key的返回结果跟单独调用返回结果一直，具体反馈结果参考各个接口对应的文档
     */
    public function query($request)
    {
        $orgData = $request;
        if (!is_array($request)) {
            return $this->getRetData('-1000700', '接口请求参数不正确！');
        }
        foreach ($request as $key => $value) {
            $getData = array();
            if (isset($value['getData']) && !empty($value['getData'])) {
                $getData = array_merge($getData, $value['getData']);
            }
            $getStr = $this->getPaasQueryParam($value['apiName'], $getData);

            unset($request[$key]['getData']);
            unset($request[$key]['apiName']);
            $request[$key]['getData'] = $getStr;

            if (isset($value['postData'])) {
                if (!is_array($value['postData']) && !is_string($value['postData'])) {
                    return $this->getRetData('-1000701', '接口请求参数不正确！');
                }
                $postStr = '';
                if (is_array($value['postData']) && isset($value['postType'])) {
                    if ($value['postType'] == '1') {
                        $postStr = json_encode($value['postData']);
                    } else if ($value['postType'] == '2') {
                        $postStr = http_build_query($value['postData']);
                    }
                    if ($postStr != '') {
                        unset($request[$key]['postData']);
                        $request[$key]['postData'] = $postStr;
                    }
                    unset($request[$key]['postType']);
                }
            }
        }

        //组合URL
        $url = $this->getPaasUrl() . '?c=Merge';
        $postData = json_encode($request);
        recordLog('批量查询接口请求数据：' . var_export($request, true), __FILE__, __LINE__);
        $res = $this->http->post($url, $postData);
        recordLog('批量查询接口返回数据：' . var_export($res, true), __FILE__, __LINE__);
        if ($res['ret'] != 0) {
            $this->tglogReport('框架请求ULink-Paas出现异常，curl_errno：' . $res['ret'] . '，curl_error：' . $res['msg'], 'Merge');
            return $this->getRetData(CURL_ERROR_NO, '系统繁忙，请稍后再试！');
        }
        $res = $res['data'];
        if ($res['ret'] != 0) {
            return $this->getRetData($res['ret'], '系统繁忙，请稍后再试！');
        }
        $rtnData = [];
        foreach ($res['resultMerge'] as $index => $item) {
            if ($item['ret'] != 0) {
                return $this->getRetData($item['ret'], '系统繁忙，请稍后再试！');
            } else {
                $data = [];
                if ($orgData[$index]['apiName'] == 'point.query' || $orgData[$index]['apiName'] == 'point.batchquery') {
                    if (isset($orgData[$index]['getData']['pointId'])) {
                        if ($item['data']['ret'] != 0) {
                            return $this->getRetData($item['data']['ret'], '系统繁忙，请稍后再试！');
                        }
                        $data[$orgData[$index]['getData']['pointId']] = [
                            'point' => $item['data']['point'],
                            'total' => $item['data']['total'],
                        ];
                    } else {
                        $data = $item['data'];
                    }
                } else if ($orgData[$index]['apiName'] == 'gameattr.sidip') {
                    $data = Common::queryString2Arr($item['data']);
                    unset($data['_idip_req_id_'], $data['_idip_req_id_']);
                } else if ($orgData[$index]['apiName'] == 'qual.query') {
                    $qualInfo = [];
                    if (is_array($orgData[$index]['postData'])) {
                        $qualInfo = $orgData[$index]['postData'];
                    } else {
                        $qualInfo = json_decode($orgData[$index]['postData']);
                    }
                    $data = $this->getQualRetData($qualInfo, $item);
                    unset($data['sPaasSerial']);
                    $data = $data['data'];
                } else {
                    $rtnData['data'][$index] = $item['data'];
                }
                $rtnData['data'][$index] = $data;
            }
        }
        return $this->getRetData(0, 'success', $rtnData);
    }
    /**
     * 批量查询
     * @param array $queryCondition 查询条件
     * [
     *      'get1' =>[
     *          'method'=>'调用接口，目前支持接口列表:Lottery_limit|Lottery_info|Qual_query|DC_Suggest|DC_Query|Point|IDIP',
     *          'resource'=>'method为Lottery_limit或者Lottery_info时填礼包单号，其他情况不需要传',
     *          'para'=>['查询条件数组']
     *      ]
     * ]
     * 注意：不需要把所有method全部写上，需要用到什么功能就对应下面示例传参
     * 
     * 例如：
     *  [
     *       "get1" => [
     *           "method"   => "Lottery_limit", //查询礼包限量情况
     *           "resource" => "礼包单号",
     *           "para"  => [
     *               "iPackageId"  => "礼包id",
     *               "iQueryQQLeft" => '0:查礼包总量，1:查qq限量'
     *           ]
     *       ],
     *       "get2" => [
     *           "method"   => "Lottery_GetCollectRecords",  //查询抽奖记录
     *           "resource" => "礼包单号",
     *           "para"  => [
     *               "iUin"  => "账号ID",
     *               "order" => "id desc"
     *           ]
     *       ],
     *       "get3" => [
     *           "method"   => "Qual_query", //资格查询
     *           "para"  => [
     *               "type" => "public_hold", //如果查公共资格，带上这个参数，普通资格去掉
     *               "key" => "资格key，不要带openid或者QQ号",
     *               "totalQualNum" => '资格总量'
     *           ]
     *       ],
     *       "get4" => [
     *          "method"   => "DC_Suggest", //挖掘接口查询
     *           "para"  => [
     *               "query" => '查询参数json格式', //例如：{"version":"1","flowid":"1","reqtype":"3","reqid":"1", "credid":"qq.lottery.poker"}
     *           ]
     *       ],
     *      "get5" => [
     *           "method"   => "DC_Query", //经分接口查询
     *           "l5" => "L5的sid",
     *           "para"  => [
     *               "query" => "请求URL和参数", //例如：/idatarealrule/getindexval/68/425/vopenid=5C43A5134EB4E16BB080A037ABE73039&platid=1&
     *           ]
     *       ],
     *       "get6" => [
     *           "method"   => "Point",  //积分查询
     *           "para" => [
     *              'sGameOpenid', //不传默认当前登录openid，传了就查指定openid的积分
     *               "iPointType" => '【必填】积分类型：0|1|2|3|4', //参考Point类中的积分类型说明
     *               "pointId" => '【必填】积分ID',
     *               "area" => '【选填】大区，根据积分账号类型决定',
     *               "platId" => '【选填】平台,根据积分账号类型决定',
     *               "partition" => '【选填】区服，根据积分账号类型决定',
     *               "roleId" => '【选填】角色ID，根据积分账号类型决定',
     *           ]
     *       ],
     *       "get7" => [
     *           "method" => "IDIP",
     *           "para" => [
     *               "query" => "查询字符串" //例如：cmd=12345&uin=2345
     *           ]
     *       ]
     *   ]
     * @return array 查询结果集
     * [
     *      'iRet' => '',
     *      'sMsg' => '',
     *      'data' =>[
     *          'get1' => [],
     *          'get2' => [],
     *          ...,
     *          'get7' => []
     *      ]
     * ]  
     */
    public function btQuery(array $queryCondition)
    {
        foreach ($queryCondition as $key => $data) {
            if (!isset($data['method']) || !in_array($data['method'], ['Lottery_limit', 'Lottery_info', 'Qual_query', 'DC_Suggest', 'DC_Query', 'Point', 'IDIP'])) {
                return ['iRet' => '-1', 'sMsg' => "批量查询的method必须传，且值必须在['Lottery_limit', 'Lottery_info', 'Qual_query', 'DC_Suggest', 'DC_Query','Point', 'IDIP']之中", 'data' => []];
            }

            if (in_array($data['method'], ['Lottery_limit', 'Lottery_info'])) {
                if (!Validate::checkMRMSID($data['resource'])) {
                    return ['iRet' => '-2', 'sMsg' => '礼包单$queryCondition' . "['{$key}']['resource']" . '错误！', 'data' => []];
                }
            } else {
                unset($queryCondition[$key]['resource']);
            }

            if ($data['method'] == 'Point') {
                if (!isset($data['para']['iPointType']) || !in_array($data['para']['iPointType'], ['0', '1', '2', '3', '4'])) {
                    return ['iRet' => '-3', 'sMsg' => '积分类型$queryCondition' . "['{$key}']['para']['iPointType']" . '错误！', 'data' => []];
                }
                if (!isset($data['para']['pointId']) || !preg_match("/^\d+(,\d+)*$/", $data['para']['pointId'])) {
                    return ['iRet' => '-4', 'sMsg' => '积分Id$queryCondition' . "['{$key}']['para']['iPointType']" . '错误！', 'data' => []];
                }
            }
        }
        //组合URL
        $url = $this->getPaasRequestUrl('tool.batchquery');
        $postData = json_encode($queryCondition);
        $res = $this->http->post($url, $postData);
        if ($res['ret'] != '0') {
            $this->tglogReport('框架请求ULink-Paas出现异常，curl_errno：' . $res['ret'] . '，curl_error：' . $res['msg'], 'tool.batchquery');
            return ['iRet' => $res['ret'], 'sMsg' => $res['msg'], 'data' => []];
        }
        $res = $res['data'];
        if ($res['ret'] != '0') {
            return ['iRet' => $res['ret'], 'sMsg' => $res['msg'], 'data' => []];
        }

        return ['iRet' => '0', 'sMsg' => 'success', 'data' => $res['data']];
    }
}
